package com.wjh.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wjh.mapper.PermissionMapper;
import com.wjh.mapper.UserMapper;
import com.wjh.pojo.LoginUser;
import com.wjh.pojo.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

@Service
public class UserDetailsServiceImpl implements org.springframework.security.core.userdetails.UserDetailsService {
    @Resource
    private UserMapper userMapper;

    @Resource
    private PermissionMapper permissionMapper;


    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        //根据用户名查询用户信息
        LambdaQueryWrapper<User> queryWrapper =
                new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUserName,s);
        //查询对应用户
        User user = userMapper.selectOne(queryWrapper);
        //判断用户是否存在,如果没查到，抛出异常
        if(Objects.isNull(user)){
            throw new RuntimeException("用户不存在");
        }
        //根据用户Id查询对应的权限信息
        List<String> permission = permissionMapper.selectPermissionById(user.getId());
        //返回
        return new LoginUser(user,permission);
    }
}
